//
//  SetViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/8/1.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "SetViewController.h"
#import "SetCell.h"
#import "SetModle.h"
#import "AboutUsViewController.h"
#import "CheckVersionAlearView.h"
#import "LanguageViewController.h"
#import "ValuationMethodViewController.h"
@interface SetViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)NSMutableArray * dataAry;
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)UIButton  * logoutButton;

@property (nonatomic,strong)NSString * url;
@property (nonatomic,strong)NSString * upgrade_point;
@property (nonatomic,assign)BOOL isUpdata;
@property (nonatomic,assign)NSInteger versionType;
@end
@implementation SetViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    if ([EXUserManager isLogin]) {
        [self.view addSubview:self.logoutButton];
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(valuationMethod) name:ValuationMethodNotificationse object:nil];
    [self getData];
    [self getVersion];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self barLine:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self barLine:NO];
}
- (void)valuationMethod
{
    [self.tableView reloadData];
}
- (void)getVersion
{
    WeakSelf
    [EXUserManager getVersion:^(NSDictionary *dic) {
        
        if (dic) {
            weakSelf.url = dic[@"apk_url"];
            weakSelf.versionType = [dic[@"type"] integerValue]; //1为建议升级，2为强制升级
            weakSelf.upgrade_point = dic[@"upgrade_point"]; //更新提示
            NSString * Version = [EXUnit getVersion];
            NSArray *array = [Version componentsSeparatedByString:@"."];
            NSString * VersionStr = [NSString stringWithFormat:@"%@%@%@",array[0],array[1],array[2]];
            NSString * version_code = [NSString stringWithFormat:@"%@%@%@",dic[@"version_id"],dic[@"version_major"],dic[@"version_minor"]]; //是否需要更新
            
            
            if (VersionStr.integerValue >= version_code.integerValue)
            {
                weakSelf.isUpdata = NO;
            }else
            {
                weakSelf.isUpdata = YES;
            }
        }else
        {
            weakSelf.isUpdata = NO;
        }
        
    }];
}
#pragma mark----数据
- (void)getData
{
    NSMutableArray * array = [[NSMutableArray alloc] init];
    [array addObject:@{@"title":Localized(@"set_Scavenging_caching"),@"content":@""}];
    [array addObject:@{@"title":Localized(@"set_About_us"),@"content":@""}];
    [array addObject:@{@"title":Localized(@"Check_update"),@"content":@""}];
    [array addObject:@{@"title":Localized(@"Setting_language"),@"content":@""}];
    if (![EXUnit isHideCurrencyPrice]) {
        [array addObject: @{@"title":Localized(@"Setting_Valuation_method"),@"content":@""}];
        
    }
    for (NSDictionary *dic in array)
    {
        
        SetModle *modle=[[SetModle alloc]init];
        modle.leftStr=dic[@"title"];
        [self.dataAry addObject:modle];
    }
    [_tableView reloadData];
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight -TABBAR_HEIGHT1 -64 -IPhoneTop)];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.backgroundColor = TABLEVIEWLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[SetCell class] forCellReuseIdentifier:@"SetCell"];
        
    }
    return _tableView;
}
- (UIButton *)logoutButton
{
    if (!_logoutButton) {
        _logoutButton = [UIButton dd_buttonCustomButtonWithFrame:CGRectMake(RealValue_H(20),
                                                                            UIScreenHeight - IPhoneBottom - RealValue_H(57)-RealValue_H(80) - 64,
                                                                            UIScreenWidth - RealValue_H(40),
                                                                            RealValue_H(80)) title:Localized(@"Exit_logon") backgroundColor:[ZBLocalized sharedInstance].C2CTextPColor titleColor:TABTITLECOLOR tapAction:^(UIButton *button) {
            
            CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"log_out_message")
                                                                                     titleStr:Localized(@"Exit_logon")
                                                                                      openUrl:@""
                                                                                      confirm:Localized(@"transaction_OK")
                                                                                       cancel:Localized(@"transaction_cancel")
                                                                                        state:2
                                                                                RechargeBlock:^{
                                                                                    
                                                                                    [EXUserManager removeUserInfo]; //清楚本地数据
                                                                                    
                                                                                    [[NSNotificationCenter defaultCenter] postNotificationName:ManualExitLogonNotificationse object:nil];
                                                                                    
                                                                                    [self.navigationController popViewControllerAnimated:YES];
                                                                                    
                                                                                    
                                                                                }];
            aleartVC.animationStyle = LXASAnimationTopShake;
            [aleartVC showLXAlertView];
        }];
        KViewRadius(_logoutButton, 2);
    }
    return _logoutButton;
}
- (NSMutableArray *)dataAry
{
    if (!_dataAry) {
        _dataAry = [[NSMutableArray alloc]init];
    }
    return _dataAry;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return RealValue_H(120);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataAry.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SetCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"SetCell"];
    cell.modle=_dataAry[indexPath.row];
    if (indexPath.row ==0)
    {
        cell.rightlable.text = [NSString stringWithFormat:@"%.2fM",[self filePath]];
    }else if (indexPath.row ==2)
    {
        cell.rightlable.text = [NSString stringWithFormat:@"V %@",[EXUnit getVersion]];
    }else if (indexPath.row ==4)
    {
        cell.rightlable.text = [EXUserManager getValuationMethod];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:[NSString stringWithFormat:@"%@ %.2fM",Localized(@"Determine_clearance"),[self filePath]]
                                                                                     titleStr:Localized(@"Cache_scavenging")
                                                                                      openUrl:@""
                                                                                      confirm:Localized(@"transaction_OK")
                                                                                       cancel:Localized(@"transaction_cancel")
                                                                                        state:2
                                                                                RechargeBlock:^{
                                                                                    
                                                                                    [self clearFile];
                                                                                    
                                                                                }];
            aleartVC.animationStyle = LXASAnimationTopShake;
            [aleartVC showLXAlertView];
        }
            break;
        case 1:
        {
            AboutUsViewController * aboutVC = [[AboutUsViewController alloc] init];
            aboutVC.title = Localized(@"set_About_us");
            [self.navigationController pushViewController:aboutVC animated:YES];
        }
            break;
        case 2:
        {
            if (self.isUpdata) {
                
                switch (self.versionType) {
                    case 1: //1为建议升级
                    {
                        [self VersionupdateWithmessage:self.upgrade_point openUrl:self.url confirm:Localized(@"Immediate_update") cancel:Localized(@"Later_update") state:2];
                    }
                        break;
                    case 2: //2为强制升级
                    {
                        [self VersionupdateWithmessage:self.upgrade_point openUrl:self.url confirm:Localized(@"Immediate_update") cancel:nil state:1];
                        
                    }
                        break;
                        
                    default:
                        break;
                }
            }else
            {
                [self VersionupdateWithmessage:Localized(@"my_latest_version") openUrl:@"" confirm:@"" cancel:Localized(@"transaction_OK") state:3];
            }
        }
            break;
        case 3:
        {
            LanguageViewController * LanguageVC = [[LanguageViewController alloc] init];
            LanguageVC.title = Localized(@"Setting_language");
            [self.navigationController pushViewController:LanguageVC animated:YES];
            
        }
            break;
        case 4:
        {
            ValuationMethodViewController * valuationMethodVC = [[ValuationMethodViewController alloc] init];
            valuationMethodVC.title = Localized(@"Setting_Valuation_method");
            [self.navigationController pushViewController:valuationMethodVC animated:YES];
            
        }
            break;
        default:
            break;
    }
}

- (void)VersionupdateWithmessage:(NSString *)message
                         openUrl:(NSString *)url
                         confirm:(NSString *)confirm
                          cancel:(NSString *)cancel
                           state:(NSInteger )state
{
    CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message
                                                                             titleStr:Localized(@"my_Version_update")
                                                                              openUrl:url
                                                                              confirm:confirm
                                                                               cancel:cancel
                                                                                state:state
                                                                        RechargeBlock:^{
                                                                            
                                                                            if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]])
                                                                            {
                                                                                
                                                                                if (@available(iOS 10.0, *)) {
                                                                                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
                                                                                } else {
                                                                                    // Fallback on earlier versions
                                                                                }
                                                                            }else
                                                                            {
                                                                                if (@available(iOS 10.0, *)) {
                                                                                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/qq-yin-le-du-jia-zhong-guo/id414603431?mt=8"] options:@{} completionHandler:nil];
                                                                                } else {
                                                                                    // Fallback on earlier versions
                                                                                }if (@available(iOS 10.0, *)) {
                                                                                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/qq-yin-le-du-jia-zhong-guo/id414603431?mt=8"] options:@{} completionHandler:nil];
                                                                                } else {
                                                                                    // Fallback on earlier versions
                                                                                }
                                                                            }
                                                                            
                                                                        }];
    aleartVC.animationStyle = LXASAnimationTopShake;
    [aleartVC showLXAlertView];
}
- (void)clearFile
{
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    
    NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
    
    NSLog ( @"cachpath = %@" , cachPath);
    
    for ( NSString * p in files) {
        
        NSError * error = nil ;
        
        NSString * path = [cachPath stringByAppendingPathComponent :p];
        
        if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
            
            [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
            
        }
        
    }
    [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject : nil waitUntilDone : YES ];
    
}
-(void)clearCachSuccess
{
    NSLog ( @" 清理成功 " );
    
    [self.tableView reloadData];
}
// 显示缓存大小
-( float )filePath
{
    
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    
    return [ self folderSizeAtPath :cachPath];
    
}
//1:首先我们计算一下 单个文件的大小

- ( long long ) fileSizeAtPath:( NSString *) filePath{
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    if ([manager fileExistsAtPath :filePath]){
        
        return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
    }
    
    return 0 ;
    
}
//2:遍历文件夹获得文件夹大小，返回多少 M（提示：你可以在工程界设置（)m）

- ( float ) folderSizeAtPath:( NSString *) folderPath{
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
    
    NSString * fileName;
    
    long long folderSize = 0 ;
    
    while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
        
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
        
    }
    
    return folderSize/( 1024.0 * 1024.0 );
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
